import {
  getMyRecord,
  deleteRecord,
  auditRecord 
} from '@/api/api'
import {
  BorrowStatus
} from '@/utils/statusMap'
import { globalRouteGuard } from "@/utils/auth";

const app = getApp()

Page({
  data: {
    records: [],
    pageIndex: 1,
    pageSize: 10,
    total: 0,
    loading: false,
    loaded: false, // 新增：标记初始数据是否已加载完成
    active: 0,
    menuTop: '',
    tabs: [{
        name: '全部',
        type: 0
      },
      {
        name: '我借到的',
        type: 2
      },
      {
        name: '我借出的',
        type: 1
      }
    ],
    // 删除相关数据
    deleteRecordId: null,
    deleteBookTitle: '',
    _tabChangeTimer: null,
    // 归还相关数据
    showReturnDialog: false,
    returnRecordId: null,
    returnBookTitle: '',
    returnTime: '', // 归还时间
    returnTimeString: '', //格式化归还时间
    minDate: new Date('2020-01-01').getTime(), // 预先计算好的最小日期时间戳
    maxDate: new Date().getTime()
  },
  
  onLoad() {
    // 使用全局路由守卫检查登录状态
    if (!globalRouteGuard('/pages/loanRecords/loanRecords')) {
      return;
    }
    this.setData({
      menuTop: getApp().machin.navBarHeight,
      // 初始化records为空数组，避免未定义状态
      records: [],
      // 设置默认归还时间为当前时间
      returnTime: new Date().getTime()
    })
    this.loadRecords()
  },

  async loadRecords() {
    if (this.data.loading) return

    this.setData({
      loading: true
    })

    try {
      const params = {
        queryData: this.data.active,
        pageIndex: this.data.pageIndex,
        pageSize: this.data.pageSize,
        orderList: []
      }

      const res = await getMyRecord(params)

      if (res.code === 200) {
        this.setData({
          records: this.data.pageIndex === 1 ?
            res.data.records :
            [...this.data.records, ...res.data.records],
          total: res.data.total,
          loaded: true // 标记初始数据加载完成
        })
      } else {
        wx.showToast({
          title: res.message || '获取记录失败',
          icon: 'none'
        })
        this.setData({ loaded: true })
      }
    } catch (err) {
      console.error('获取借阅记录失败:', err)
      wx.showToast({
        title: '获取记录失败',
        icon: 'none'
      })
      this.setData({ loaded: true })
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  onTabChange(event) {
    // 清除之前的定时器，防止快速切换时重复发送请求
    if (this.data._tabChangeTimer) {
      clearTimeout(this.data._tabChangeTimer);
    }
    
    // 设置新的定时器，进行防抖处理
    const timer = setTimeout(() => {
      this.setData({
        active: event.detail.name,
        pageIndex: 1,
        records: [],
        loaded: false // 切换标签时重置加载状态
      }, () => {
        this.loadRecords();
      });
    }, 300); // 设置300ms的防抖延迟
    
    this.setData({
      _tabChangeTimer: timer
    });
  },

  loadMore() {
    if (this.data.records.length < this.data.total) {
      this.setData({
        pageIndex: this.data.pageIndex + 1
      }, () => {
        this.loadRecords()
      })
    }
  },

  onClickLeft() {
    wx.navigateBack()
  },

  getStatusText(status) {
    return BorrowStatus.text[status] || '未知状态'
  },

  getStatusClass(status) {
    return BorrowStatus.class[status] || ''
  },
  
  // 点击图片放大预览
  previewImage(e) {
    const current = e.currentTarget.dataset.src;
    wx.previewImage({
      current: current,
      urls: [current],
      showmenu: true
    })
  },
  
  // 长按处理，根据当前激活的标签页决定显示删除还是归还对话框
  // 添加日期格式化方法
  formatDate(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  
  // 添加日期选择确认方法
  onDateTimeConfirm(e) {
    // 保存用户选择的日期
    this.setData({
      returnTime: e.detail,
      returnTimeString: this.formatDate(e.detail)
    });
  },
  
  // 修改onLongPress方法，移除不必要的重置
  onLongPress(e) {
    const id = e.currentTarget.dataset.id;
    const title = e.currentTarget.dataset.title;
    
    // 当切换到'我借出的'一栏时（active === 1），显示归还对话框
    if (this.data.active === 1) {
      // 如果之前已经选择过日期，则保持该日期，否则设置为当前日期
      const currentTime = this.data.returnTime || new Date().getTime();
      
      this.setData({
        returnRecordId: id,
        returnBookTitle: title,
        showReturnDialog: true,
        returnTime: currentTime
      });
    } else {
      // 其他情况下显示删除对话框
      this.onShowDeleteDialog(e);
    }
  },
  
  // 长按显示删除对话框
  onShowDeleteDialog(e) {
    const id = e.currentTarget.dataset.id;
    const title = e.currentTarget.dataset.title;
    
    this.setData({
      deleteRecordId: id,
      deleteBookTitle: title
    });
    
    // 使用 wx.showModal 显示确认删除对话框
    wx.showModal({
      title: '确认删除',
      content: `确定要删除《${title}》这条借阅记录吗？`,
      confirmColor: '#ee0a24',
      success: (res) => {
        if (res.confirm) {
          this.onDeleteConfirm();
        } else if (res.cancel) {
          this.onDeleteCancel();
        }
      }
    });
  },
  
  // 确认删除
  onDeleteConfirm() {
    if (!this.data.deleteRecordId) return;
    
    deleteRecord(this.data.deleteRecordId).then(response => {
      if (response.code === 200) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 删除成功后重新拉取借阅记录
        this.setData({
          pageIndex: 1,
          records: [],
          loaded: false, // 重新加载时重置加载状态
          deleteRecordId: null,
          deleteBookTitle: ''
        }, () => {
          this.loadRecords();
        });
      } else {
        wx.showToast({
          title: response.message || '删除失败',
          icon: 'none'
        });
        
        this.setData({
          deleteRecordId: null,
          deleteBookTitle: ''
        });
      }
    }).catch(err => {
      console.error('删除记录失败:', err);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
      
      this.setData({
        deleteRecordId: null,
        deleteBookTitle: ''
      });
    });
  },
  
  // 取消删除
  onDeleteCancel() {
    this.setData({
      deleteRecordId: null,
      deleteBookTitle: ''
    });
  },
  
  // 关闭归还对话框
  onCloseReturnDialog() {
    this.setData({
      showReturnDialog: false,
    });
		setTimeout(()=>{
			this.setData({
				returnBookTitle: '',
				returnRecordId: null,
				returnTime: '',
				returnTimeString: ''
			})
		},500)
  },
  // 确认归还
  async onReturnConfirm() {
    if (!this.data.returnRecordId || !this.data.returnTime) {
      wx.showToast({
        title: '请选择归还时间',
        icon: 'none'
      });
      return;
    }

    const returnTimeString = new Date(this.data.returnTime).toISOString();
    // 调用归还书籍的API
  await auditRecord({
      id: this.data.returnRecordId,
      returnTime: returnTimeString
    }).then(response => {
      if (response.code === 200) {
        wx.showToast({
          title: '归还成功',
          icon: 'success'
        });
        
        // 归还成功后重新拉取借阅记录
        this.setData({
          pageIndex: 1,
          records: [],
          loaded: false,
          showReturnDialog: false,
          returnRecordId: null,
          returnBookTitle: '',
          returnTime: '',
          returnTimeString: ''
        }, () => {
          this.loadRecords();
        });
      } else {
        wx.showToast({
          title: response.message || '归还失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('归还书籍失败:', err);
      wx.showToast({
        title: '归还失败',
        icon: 'none'
      });
    });
  },
  
  // 在页面卸载时清除定时器，避免内存泄漏
  onUnload() {
    if (this.data._tabChangeTimer) {
      clearTimeout(this.data._tabChangeTimer);
    }
  }
})